<template>
  <div class="reg">
    <Logo />
    <Form @submit="onSubmit">
      <cell-group inset>
        <field
          v-model="userName"
          name="userName"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <field
          v-model="rePwd"
          type="password"
          name="rePwd"
          label="确认密码"
          placeholder="请再次输入密码"
          :rules="[{ required: true, message: '请再次填写密码' }]"
        />
      </cell-group>
      <div style="margin: 16px">
        <Button round block type="primary" native-type="submit"> 提交 </Button>
      </div>
    </Form>
    <Router-link :to="{ name: 'login' }" class="link-to"
      >已有账号？点击去登录</Router-link
    >
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Form, Field, CellGroup, Button, Toast } from "vant";
import Logo from "../publics/Logo.vue";
import { regAPI } from "../server/auth";
import { setToken } from "../utils/auth";
import { useCart } from "../store/carts-num";

const store = useCart();
const { loadCart } = store;
const { push } = useRouter();
const userName = ref("");
const password = ref("");
const rePwd = ref("");
const onSubmit = (values) => {
  // console.log("submit", values);
  if (password.value == rePwd.value) {
    regAPI({ userName: values.userName, password: values.password }).then(
      (res) => {
        if (res.code === 1) {
          Toast.success("注册成功");
          loadCart();
          setToken(res.data);
          setTimeout(() => {
            push({
              name: "user",
            });
          }, 2000);
        } else {
          Toast.fail(res.data);
        }
      }
    );
  } else {
    Toast.fail("两次输入的密码不一致");
  }
};
</script>
